<template>
	<view class="layout">
		<post-nav-bar title="智能厨房"></post-nav-bar>

		<view class="banner">
			<image :src="getWebImage('banner/kitchen_banner.jpg')" mode="aspectFill"></image>
		</view>
		<view class="white-space" v-if="tabList.length == 0">
			<uni-icons type="calendar" size="60" color="#999"></uni-icons>
			<view>
				点击创建我的智能厨房，开启健康之旅
			</view>
		</view>
		<view class="content" v-else>
			<up-cate-tab class="cate-tab" :tabList="tabList" tabKeyName="title" itemKeyName="title">
				<template #pageItem="{pageItem}">
					<view class="w-full">
						<up-cell-group :border='false'>
							<up-cell :border='false'>
								<template #right-icon>
									<up-image class="img" :src="findImgById(locationId[pageItem.index])" width="60px"
										height="60px" mode="widthFix"></up-image>
								</template>
								<template v-slot:title>
									<view class="location-box">
										<text class="location-text">存储： </text>

										<text>{{findLocationById(locationId[pageItem.index])}}</text>
										<up-select class="location-content" v-model:current="locationId[pageItem.index]"
											label="" :options="cateList"></up-select>
									</view>
								</template>
								<template v-slot:label>
									<view class="label-box">
										<view class="advice">时间：<br></view>
										<text>{{ pageItem.createdAt }}</text>
										<view class="advice">建议：<br></view>
										<view class="content-wrapper">
										  <u--text 
											  :text="pageItem.storageAdvice" 
											  class="advice-text"
											  :lines="2"
											  mode="ellipsis"
										  ></u--text>
										  <text 
											  class="detail-btn"
											  v-if="pageItem.storageAdvice?.length > 16"
											  @click="showPopupAdvice(pageItem.index)"
										  >详情</text>
										</view>
									</view>
								</template>
								<template v-slot:value>
									<view class="quantity-box">
										<view class="up">
											<view class="quantity-text">存量:</view>
											<view>
												<input v-model="pageItem.unit" class="quantity-unit" />
											</view>
										</view>
										<up-number-box class="mid" v-model="quantitys[pageItem.index]"></up-number-box>
										<button class="down" @click="del_food(pageItem.index)">删除</button>
									</view>
								</template>
							</up-cell>
						</up-cell-group>
						<!-- 弹窗组件 -->
						<u-popup :show="activePopup === pageItem.index" @close="activePopup = null" mode="center" round="10" :closeable="true">
						  <view class="popup-content">
							  <text class="popup-title">详细建议</text>
							  <scroll-view scroll-y class="advice-scroll">
								  <text class="full-advice">{{ pageItem.storageAdvice }}</text>
							  </scroll-view>
						  </view>
						</u-popup>
					</view>
				</template>
			</up-cate-tab>
		</view>

		<view class="recommendBtn">
			<up-button color="#FF4D4F" shape="circle" icon="tags" icon-color="white"
				@click="showPopup = true"></up-button>
		</view>
		<view class="button">
			<button class="add-btn" @click="add_modal = true">添加</button>
			<button class="save-btn" @click="save">保存</button>
		</view>

		<up-popup :show="showPopup" mode="left" @close="closePopup" @open="openPopup">
			<view class="popup">
				<up-text class="popup-title" text="推荐菜品" size="20" color="#FF4D4F"></up-text>
				<up-text class="popup-content" :text="recommendText" size="16"></up-text>
				<up-divider class="popup-divider" text="根据现有食材为您推荐"></up-divider>
				<up-button color="#FF4D4F" :plain="true" icon="reload" text="换一批" @click="reload"></up-button>
			</view>
		</up-popup>

		<up-modal :show="add_modal" title="添加食材" @confirm="add_food" @cancel="add_modal = false" confirmColor="#FF4D4F"
			showCancelButton>
			<view class="slot-content">
				<form @submit="add_food">
					<view class="uni-form-item">
						<view class="ingredientName">
							<uni-icons type="cart" size="30" color="#FF4D4F"></uni-icons>
							<input v-model="food.ingredientName" class="input" type="text" placeholder="输入食材名称"
								maxlength="20" />
						</view>
						<view class="tip" v-if="tip.ingredientName !== ''">{{tip.ingredientName}}</view>
					</view>
					<view class="uni-form-item">
						<view class="quantity">
							<uni-icons type="list" size="30" color="#FF4D4F"></uni-icons>
							<input v-model="food.quantity" class="input" type="text" placeholder="输入食材数量"
								maxlength="20" />
						</view>
						<view class="tip" v-if="tip.quantity !== ''">{{tip.quantity}}</view>
					</view>

					<view class="uni-form-item">
						<view class="unit">
							<uni-icons type="smallcircle" size="30" color="#FF4D4F"></uni-icons>
							<input v-model="food.unit" class="input" type="text" placeholder="输入计量单位" maxlength="20" />
						</view>
						<view class="tip" v-if="tip.unit !== ''">{{tip.unit}}</view>
					</view>
					<view class="uni-form-item">
						<view class="location" @click="location_picker = true;">
							<view>
								<text class="select-location-title" style="color: grey;">选择存储位置</text>
							</view>
							<view class="select-location-content">
								{{food.location}}
							</view>
							<view class="select-location-icon">
								<up-icon name="arrow-right"></up-icon>
							</view>
						</view>
					</view>
					<up-picker :show="location_picker" :columns="picker_data"
						@confirm="(e) => {food.location = e.value[0];location_picker = false;}"
						@cancel="location_picker = false;" :closeOnClickOverlay="true" @close="location_picker = false;"
						confirmColor="#FF4D4F"></up-picker>

				</form>
			</view>
		</up-modal>

	</view>
</template>

<script setup>
	import {
		onMounted,
		ref,
		reactive
	} from 'vue';
	import {
		appUrl
	} from '../../main';

	const showPopup = ref(false);

	function openPopup() {
		showPopup.value = true;
	}

	function closePopup() {
		showPopup.value = false;
	}

	const recommendText = ref('');

	const userId = uni.getStorageSync("userId");
	const getRecommend = () => {
		uni.showToast({
			icon:'loading',
			title:"正在生成",
			duration: 10000
		})
		uni.request({
			url: `http://120.26.113.115:5000/recommend_meal/${userId}`,
			method: "GET"
		}).then(res => {
			recommendText.value = res.data.recommend;
			uni.showToast({
				title: "成功"
			})
		})
	}
	const reload = () => {
		getRecommend();
	}

	//令牌
	const token = ref("")
	//添加食材窗口开关
	const add_modal = ref(false)
	//位置存储选择器开关
	const location_picker = ref(false)
	//数据选择器
	const picker_data = reactive([
		["冰箱", "橱柜", "地面", "篮子"]
	])
	//添加食材的数据结构
	const food = ref({
		ingredientName: "",
		quantity: "",
		unit: "",
		location: "冰箱"
	})
	//验证失败提示
	const tip = reactive({
		ingredientName: "",
		quantity: "",
		unit: "",
	})
	//返回数据
	let backData = []


	//分解数据
	const inventoryIds = ref([])
	const locationId = ref([]) //存贮位置数据
	const quantitys = ref([]) //存储数量数据
	const tabList = ref([]); //存储内容数据

	//位置处理映射
	const locationMapping = {
		"冰箱": '0',
		"橱柜": '1',
		"篮子": '2',
		"地面": '3'
	};

	//下拉列表
	const cateList = ref([{
			id: '0',
			name: '冰箱',
			img: "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/logo/bingxiang.png"
		},
		{
			id: '1',
			name: '橱柜',
			img: "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/logo/chugui.png"
		},
		{
			id: '2',
			name: '篮子',
			img: "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/logo/lanzi.png"
		},
		{
			id: '3',
			name: "地面",
			img: "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/logo/dimian.png"
		}
	])



	const findLocationById = (id) => {
		const item = cateList.value.find(item => item.id === id);
		return item ? item.name : '未找到';
	}
	const findImgById = (id) => {
		const item = cateList.value.find(item => item.id === id);
		return item ? item.img : '未找到';
	}

	const add_food = () => {
		if (validation()) {
			const now = new Date();
			const year = now.getFullYear(); // 年份
			const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份（注意：getMonth() 返回值为0-11）
			const day = String(now.getDate()).padStart(2, '0'); // 日
			const hours = String(now.getHours()).padStart(2, '0'); // 小时
			const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟
			const seconds = String(now.getSeconds()).padStart(2, '0'); // 秒
			food.value.createdAt = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			uni.request({
				url: appUrl + "/ingredient/add",
				header: {
					token: uni.getStorageSync("token")
				},
				data: food.value,
				method: "POST",
				success: (res) => {
					// 第一个请求成功，处理 res
					console.log("添加成功", res);
					const inventory_id = res.data.data.inventoryId
					// 紧接着调用第二个接口（例如获取列表）
					uni.request({
					  url: `http://120.26.113.115:5000/get_storage_advice/${inventory_id}`, // 假设是 GET 请求
					  header: { token: uni.getStorageSync("token") },
					  method: "GET",
					  success: (res2) => {
						const item = res2.data.data
						// 库存id
						inventoryIds.value.push(item.inventoryId)
						// 获取存储位置对应的ID
						locationId.value.push(locationMapping[item.location]);
						// 添加数量
						quantitys.value.push(item.quantity);
						
						console.log(tabList.value);
						// 构建tabList
						tabList.value.push({
							title: item.ingredientName,
							children: [{
								index: tabList.value.length,
								unit: item.unit,
								createdAt: item.createdAt,
								storageAdvice: item.storageAdvice,
							}]
						});
						add_modal.value = false
						uni.showToast({
							title: "添加成功",
							duration: 1000
						})
						console.log(tabList.value);
					  },
					  fail: (err2) => {
						console.error("获取列表失败", err2);
					  }
					});
				  },
				  fail: (err) => {
					console.error("添加失败", err);
				  }
			}).then(res => {})
		}
	}


	const validation = () => {
		if (food.value.ingredientName == "") {
			tip.ingredientName = "食材名称不能为空"
			return false
		} else if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(food.value.quantity)) {
			tip.quantity = "数量必须为正数"
			return false
		} else if (food.value.unit == "") {
			tip.unit = "单位不能为空"
			return false
		}
		return true
	}

	const del_food = (index) => {
		uni.showModal({
			title: '删除',
			content: '确定要删除食材吗？',
			confirmColor: "#FF4D4F",
			success: function(res) {
				if (res.confirm) {
					const id = inventoryIds.value[index]
					inventoryIds.value.splice(index, 1)
					locationId.value.splice(index, 1)
					quantitys.value.splice(index, 1)
					tabList.value.splice(index, 1)
					tabList.value.forEach((item, i) => {
						item.children[0].index = i;
					});
					uni.request({
						url: appUrl + "/ingredient/delete",
						header: {
							token: token.value
						},
						data: {
							inventoryId: id
						},
						method: "POST"
					}).then(res => {
						console.log(res.data.data);
					})
					uni.showToast({
						title: "删除成功",
						duration: 1000
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	const save = () => {
		saveData()
		uni.request({
			url: appUrl + "/ingredient/update",
			header: {
				token: token.value
			},
			data: backData,
			method: "POST"
		}).then(res => {
			console.log(res.data.data);
		})

		uni.showToast({
			title: "保存成功",
			duration: 1000
		})
	}


	const getWebImage = (path) => {
		return "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/" + path
	}

	const dataInit = (rawData) => {
		rawData.forEach((item, index) => {
			// 库存id
			inventoryIds.value.push(item.inventoryId)
			// 获取存储位置对应的ID
			locationId.value.push(locationMapping[item.location]);
			// 添加数量
			quantitys.value.push(item.quantity);
			// 构建tabList
			tabList.value.push({
				title: item.ingredientName,
				children: [{
					index: index,
					unit: item.unit,
					createdAt: item.createdAt,
					storageAdvice: item.storageAdvice,
				}]
			});
		});
	}



	const saveData = () => {
		tabList.value.forEach((item, index) => {
			// 获取当前条目的详细信息
			const detail = item.children[0];
			// 创建新的条目
			backData.push({
				inventoryId: inventoryIds.value[index],
				ingredientName: item.title,
				quantity: quantitys.value[index],
				unit: detail.unit,
				createdAt: detail.createdAt,
				storageAdvice: detail.storageAdvice,
				location: locationMapping[locationId.value[index]]
			});
		});

	}

	onMounted(() => {
		token.value = uni.getStorageSync("token")
		if (token.value === null || token.value === "") {
			uni.showToast({
				icon: 'error',
				title: "用户未登录",
				duration: 1000
			})
			uni.reLaunch({
				url: "/pages/UserView/UserView"
			})
		} else {
			uni.request({
				url: appUrl + "/ingredient/get",
				header: {
					token: token.value
				},
				method: "GET"
			}).then(res => {
				dataInit(res.data.data)
			})

		}
		getRecommend();
	})
	
	const activePopup = ref(null); // 当前激活的弹窗索引
	
	const showPopupAdvice = (index) => {
	    activePopup.value = index;
	};
</script>

<style lang="scss" scoped>
	.layout {
		.banner {
			width: 100%;

			image {
				width: 100%;
				height: 200rpx;
			}
		}

		.popup {
			padding: 40rpx;
		}
		.popup-title {
			padding-top: 40rpx;
		}
		.popup-content {
			padding-top: 20rpx;
		}

		.white-space {
			width: 100%;
			height: 80vh;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #999;
		}

		.content {
			.cate-tab {
				height: calc(100vh - 150px);
				/* #ifdef H5 */
				height: calc(100vh - 150px - var(--window-top));
				/* #endif */

				.location-box {
					width: 230rpx;
					margin: 10rpx 0 10rpx 0;
					display: flex;

					.location-text {
						color: #999;
					}
				}

				// 在现有样式最后追加
				.label-box {
					width: 230rpx;
					.time {
						color: #999;
						margin-bottom: 10rpx;
					}
					.advice-container {
						.label {
							color: #999;
							display: block;
							margin-bottom: 5rpx;
						}
						.content-wrapper {
							position: relative;
							padding-right: 80rpx;
							.advice-text {
								color: #666;
								line-height: 1.5;
								font-size: 14px;
							}
							.detail-btn {
								position: absolute;
								right: 0;
								bottom: 0;
								color: #FF4D4F !important;
								font-size: 12px;
								padding: 2px 8px;
								background-color: rgba(255,77,79,0.1);
								border-radius: 12px;
							}
						}
					}
				}
				
				.popup-content {
					width: 80vw;
					max-height: 70vh;
					padding: 20px;
					.popup-title {
						display: block;
						font-size: 16px;
						font-weight: bold;
						margin-bottom: 15px;
						text-align: center;
					}
					.advice-scroll {
						max-height: 60vh;
						.full-advice {
							white-space: pre-line;
							line-height: 1.5;
							color: #666;
						}
					}
				}

				.quantity-box {
					width: 180rpx;

					.up {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 20rpx;

						.quantity-text {
							width: 100rpx;
						}

						.quantity-unit {
							padding-left: 10rpx;
							width: 70rpx;
							border: 1px solid #aaa;
							border-radius: 7px;
						}
					}

					.mid {
						margin-bottom: 25rpx;
					}

					.down {
						margin-top: 10rpx;
						width: 100%;
						height: 50rpx;
						font-size: 15px;
						padding: 5rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						background-color: #fff;
						border: 1px solid #FF4D4F;
						color: #FF4D4F;
					}
				}

				.img {
					margin-left: 20rpx;

				}

			}
		}

		.recommendBtn {
			position: fixed;
			bottom: 120rpx;
			right: 70rpx;
		}

		.button {
			position: fixed;
			/* 使用固定定位 */
			bottom: 0;
			/* 距离底部的距离 */
			left: 0;
			/* 距离左边的距离 */
			width: 100%;
			/* 按钮宽度占满整个屏幕宽度 */
			padding: 10rpx 50rpx;
			/* 内边距 */
			height: 90rpx;
			display: flex;
			justify-content: space-between;

			.add-btn {
				width: 45%;
				height: 60rpx;
				background-color: #fff;
				border: 1px solid #FF4D4F;
				color: #FF4D4F;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
				letter-spacing: 20rpx;
			}

			.save-btn {
				width: 45%;
				height: 60rpx;
				background-color: #FF4D4F;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
				letter-spacing: 20rpx;
			}
		}

		.slot-content {
			margin: 20rpx 0;
			padding: 0 50rpx;

			.tip {
				width: 100%;
				height: auto;
				padding-left: 30rpx;
				color: #FF4D4F;
			}

			.uni-form-item {
				height: 100rpx;
				margin: 0 0 30rpx 0;

				.ingredientName,
				.quantity,
				.unit {
					width: 100%;
					background-color: #fff;
					border-radius: 50px;
					height: 100rpx;
					display: flex;
					justify-content: left;
					align-items: center;
					padding: 0 30rpx;

					input {
						margin-left: 20rpx;
					}
				}

				.location {
					padding: 30rpx;
					display: flex;
					align-items: center;

					.select-location-content {
						display: flex;
						padding-left: 50rpx;
					}

					.select-location-icon {
						margin-left: auto;
					}
				}

				&.vertify-box {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.vertify {
						width: 100%;
						background-color: #fff;
						border-radius: 50px;
						height: 100rpx;
						display: flex;
						justify-content: left;
						align-items: center;
						padding: 0 30rpx;

						input {
							margin-left: 20rpx;
						}
					}

					.vcode-btn {
						width: 400rpx;
						font-size: 15px;
						margin-left: 10rpx;
						height: 80rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #FF4D4F;
						border: 2px #FF4D4F solid;
					}
				}
			}
		}

	}
</style>